//
//  HECartViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/26.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HECartViewController.h"
#import "HEGoodsDetailsFooterView.h"
#import "HEGoodsDetailsViewController.h"
#import "HECartDataModel.h"
#import "HECartHeaderCell.h"
#import "HECartItemCell.h"
#import "HECartFooterCell.h"
#import "HEShopCarModel.h"
#import "HECartTabBarView.h"
#import "HECreateOrderViewController.h"
#import "HEAllCategViewController.h"

@interface HECartViewController ()<UITableViewDelegate, UITableViewDataSource, HECartHeaderCellDelegate, HECartItemCellDelegate, HECartTabBarViewDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) HECartTabBarView *tabbar;
@property (nonatomic, strong) UIView *headView;

@property (nonatomic, strong) HECartDataModel *cartData;
@property (nonatomic, strong) NSMutableArray <HEShopCarHeadModel *>*cartsDataSource;

@property (nonatomic, strong) NSMutableArray <HEShopCarModel *>*selectGoods;


@end

@implementation HECartViewController

- (NSMutableArray<HEShopCarHeadModel *> *)cartsDataSource {
    if (!_cartsDataSource) {
        _cartsDataSource = [NSMutableArray array];
    }
    return _cartsDataSource;
}

- (NSMutableArray<HEShopCarModel *> *)selectGoods {
    if (!_selectGoods) {
        _selectGoods = [NSMutableArray array];
    }
    return _selectGoods;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"购物车";
    
    [self initUI];
    [self initTabBar];
}

- (void)initUI {

    // 设置导航栏按钮
    [self zx_setRightBtnWithText:@"管理" clickedBlock:^(UIButton * _Nonnull btn) {
        
        if (self.tabbar.actionType == HECartTabBarActionTypeSettlement) {
            [self.zx_navRightBtn setTitle:@"取消" forState:UIControlStateNormal];
            self.tabbar.actionType = HECartTabBarActionTypeDelete;
        }else if(self.tabbar.actionType == HECartTabBarActionTypeDelete) {
            [self.zx_navRightBtn setTitle:@"管理" forState:UIControlStateNormal];
            self.tabbar.actionType = HECartTabBarActionTypeSettlement;
        }
    }];
    self.zx_navRightBtn.zx_tintColor = CNavBgColor;
    
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - (55 + KSafeTabbarHeight)) style:UITableViewStyleGrouped];
    _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
            
    //头部刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    _tableView.mj_header = header;
    //
    //        //底部刷新
    //        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
    ////        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
    ////        _tableView.mj_footer.ignoredScrollViewContentInsetBottom = 30;

    _tableView.scrollsToTop = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = CViewBgColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    
    [self.tableView registerClass:[HECartHeaderCell class] forCellReuseIdentifier:@"HECartHeaderCell"];
    [self.tableView registerClass:[HECartItemCell class] forCellReuseIdentifier:@"HECartItemCell"];
    [self.tableView registerClass:[HECartFooterCell class] forCellReuseIdentifier:@"HECartFooterCell"];
    
    [self initHeadView];
    [self initFooterView];

    [_tableView reloadData];
}

- (void)initTabBar {
    _tabbar = [HECartTabBarView new];
    _tabbar.delegate = self;
    [self.view addSubview:_tabbar];
    
    CGFloat tabHeight = 55 + KSafeTabbarHeight;
    [_tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(tabHeight);
    }];
}

- (UIView *)headView {
    if (!_headView) {
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 300)];
        
        UIImageView *imgView = [UIImageView new];
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.image = IMAGE_NAMED(@"no_data");
        [headView addSubview:imgView];
        
        UILabel *noticeLb = [UILabel new];
        noticeLb.text = @"这里什么都没有~";
        noticeLb.font = DYFont(16);
        noticeLb.textAlignment = NSTextAlignmentCenter;
        [headView addSubview:noticeLb];
        
        // 挑选
        QMUIFillButton *tobtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
        tobtn.titleLabel.font = UIFontMake(16);
        [tobtn setBackgroundColor:CNavBgColor];
        [tobtn setTitle:@"去挑选" forState:UIControlStateNormal];
        [headView addSubview: tobtn];
        [tobtn addTarget:self action:@selector(toSelectClick) forControlEvents:UIControlEventTouchUpInside];
        
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headView).mas_offset(30);
            make.centerX.equalTo(headView);
            make.right.left.equalTo(headView);
            make.height.mas_offset(imgView.image.size.height);
         }];
        
        [noticeLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imgView.mas_bottom);
            make.centerX.equalTo(headView);
            make.right.left.equalTo(headView);
        }];
        
        [tobtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(noticeLb.mas_bottom).mas_offset(20);
            make.centerX.equalTo(headView);
            make.width.mas_greaterThanOrEqualTo(125);
            make.height.mas_offset(40);
         }];
        _headView = headView;
    }
    return _headView;
}

- (void)initHeadView {
    self.tableView.tableHeaderView = self.headView;
}

- (void)initFooterView {
    HEGoodsDetailsFooterView *footerView = [[HEGoodsDetailsFooterView alloc] initWithFrame:CGRectMake(0, 300, KScreenWidth, 0)];
    self.tableView.tableFooterView = footerView;
    [footerView getFooterViewHeightBlock:^(CGFloat height) {
        footerView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, height);
        [self.tableView reloadData];
    }];
    
    [footerView didSelectItemAtFooterView:^(HEGoodsModel * _Nonnull model) {
        HEGoodsDetailsViewController *vc = [[HEGoodsDetailsViewController alloc] init];
        vc.goodsId = model.id;
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

#pragma mark - refresh

- (void)loadData {
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KCartLits parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.cartData = [HECartDataModel mj_objectWithKeyValues:response.data];
        
        [self dealData];
        
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)dealData {
    
    
    NSMutableArray *oldArr = [NSMutableArray arrayWithArray:self.cartsDataSource.copy];
    
    [self.cartsDataSource removeAllObjects];
//    self.cartsDataSource = @[].mutableCopy;
    if (!self.cartData.cartItemList.count) {
        self.tableView.tableHeaderView = self.headView;
    }else {
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    }
    
    for (HECartItemModel *item in self.cartData.cartItemList) {
        
        HEShopCarHeadModel *headModel = [HEShopCarHeadModel new];
        headModel.storeName = item.storeName;
        headModel.storeId = item.storeId;
        
        BOOL isExit = NO;
        for (HEShopCarHeadModel *head in self.cartsDataSource) {
            isExit = [head isEqual:headModel];
            if (isExit) {
                break;
            }
        }
        if (!isExit) {
            [self.cartsDataSource addObject:headModel];
        }
    }
    
    for (HEShopCarHeadModel *head in self.cartsDataSource) {
        for (HECartItemModel *item in self.cartData.cartItemList) {
            if (item.storeId == head.storeId) {
                HEShopCarModel *goodModel = [HEShopCarModel new];
                goodModel.storeName = item.storeName;
                goodModel.storeId = item.storeId;
                goodModel.productName = item.productName;
                goodModel.productAttr = item.productAttr;
                goodModel.quantity = item.quantity;
                goodModel.productId = item.productId;
                goodModel.productPic = item.productPic;
                goodModel.price = item.price;
                goodModel.id = item.id;
                goodModel.headModel = head;

                [head.goodsList addObject:goodModel];
            }
         }
    }
    
    // 复原选择
    for (HEShopCarHeadModel *oldHead in oldArr) {
        
       for (HEShopCarHeadModel *newHead in self.cartsDataSource) {

           if (oldHead.storeId == newHead.storeId) {
               newHead.isChoose = oldHead.isChoose;
           }
           
           for (HEShopCarModel *olditem in oldHead.goodsList) {
               for (HEShopCarModel *newitem in newHead.goodsList) {
                    if (olditem.id == newitem.id) {
                        newitem.isChoose = olditem.isChoose;
                    }
               }
           }
       }
    }
        
    [self calculateEnd];
    [_tableView reloadData];
}

#pragma mark -

- (void)toSelectClick {
    HEAllCategViewController *vc = [HEAllCategViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)headerRereshing {
    [self loadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cartsDataSource.count;
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HEShopCarHeadModel *model = self.cartsDataSource[section];
    return model.goodsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEShopCarHeadModel *model = self.cartsDataSource[indexPath.section];
    HEShopCarModel *goodModel = model.goodsList[indexPath.row];
    HECartItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HECartItemCell"];
    cell.model = goodModel;
    cell.delegate = self;
    return cell;
}

#pragma mark -

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HEShopCarHeadModel *model = self.cartsDataSource[indexPath.section];
    HEShopCarModel *goodModel = model.goodsList[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: @"HECartItemCell" cacheByIndexPath:indexPath configuration:^(HECartItemCell *cell) {
        cell.model = goodModel;
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEShopCarHeadModel *model = self.cartsDataSource[indexPath.section];
    HEShopCarModel *goodModel = model.goodsList[indexPath.row];
    HEGoodsDetailsViewController *vc = [[HEGoodsDetailsViewController alloc] init];
    vc.goodsId = goodModel.productId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 25;
}

// tableView的sectionHeader加载数据
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HEShopCarHeadModel *model = self.cartsDataSource[section];
    HECartHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HECartHeaderCell"];
    cell.model = model;
    cell.delegate = self;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    HECartFooterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HECartFooterCell"];
    return cell;
}

#pragma mark - HECartHeaderCellDelegate
- (void)carHeadSelect:(HECartHeaderCell *)cell withModel:(HEShopCarHeadModel *)model {
    
    [self changeHeadSelectSatate:model];
    
    [self calculateEnd];

    [_tableView reloadData];
}

// 改变某个段的所有选中状态
- (void)changeHeadSelectSatate:(HEShopCarHeadModel *)head {
    if (head.isChoose) {
          // 区中的所有cell都选中
          [head.goodsList enumerateObjectsUsingBlock:^(HEShopCarModel  *_Nonnull goodModel, NSUInteger idx, BOOL * _Nonnull stop) {
            goodModel.isChoose = YES;
          }];
      }else {
          // 区中的所有cell都取消选中
          [head.goodsList enumerateObjectsUsingBlock:^(HEShopCarModel  *_Nonnull goodModel, NSUInteger idx, BOOL * _Nonnull stop) {
            goodModel.isChoose = NO;
          }];
    }
}

#pragma mark - HECartItemCellDelegate
- (void)goodsCellSelect:(HECartItemCell *)cell withModel:(HEShopCarModel *)model {
    
    // 判断section是否全选
    BOOL isAllSelect = YES;
    for (HEShopCarModel *goodModel in model.headModel.goodsList) {
        if (!goodModel.isChoose) {
            isAllSelect = NO;
            break;
        }
    }
    model.headModel.isChoose = isAllSelect;
    
    [self calculateEnd];
    [_tableView reloadData];
}

- (void)updateGoodsQuantity:(HECartItemCell *)cell withNum:(NSInteger)total changheType:(HECartTotalChangeType)type{
    [self calculateEnd];

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KCartUpdateQuantity parameters:@{@"quantity":[NSNumber numberWithInteger:total], @"id":[NSNumber numberWithInteger:cell.model.id]} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (!response.success) {
            [self resetGoodsTotal:cell total:total changheType:type];
        }
    } failure:^(NSError * _Nonnull error) {
        [self resetGoodsTotal:cell total:total changheType:type];
    }];
}

// 复原购物车商品数量
- (void)resetGoodsTotal:(HECartItemCell *)cell total:(NSInteger)total changheType:(HECartTotalChangeType)type {
    if (type == HECartTotalChangeTypeAdd) {
        cell.model.quantity = total-1;
    }else if (type == HECartTotalChangeTypeCut){
        cell.model.quantity = total+1;
    }
    [self calculateEnd];
    [self.tableView reloadData];
}

#pragma mark - HECartTabBarViewDelegate
- (void)tabbarSelectAll:(BOOL)select {
    for (HEShopCarHeadModel *head in self.cartsDataSource) {
        head.isChoose = select;
        [self changeHeadSelectSatate:head];
    }
    [self calculateEnd];
    [_tableView reloadData];
}

- (void)tabbarDidSelectWithActionType:(HECartTabBarActionType)type {
    
    if (type == HECartTabBarActionTypeDelete) {
        
        NSMutableArray *idArrs = [NSMutableArray array];
        
        if (!_selectGoods.count) {
            [Dialog toast:@"请选择要删除的商品~" delay:2.0];
            return;
        }
        
        for (HEShopCarModel *goods in _selectGoods) {
            [idArrs addObject: [NSNumber numberWithInteger:goods.id]];
        }
                
        [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KCartDelete parameters:@{@"cart_id_list": [idArrs componentsJoinedByString:@","]} success:^(id  _Nonnull responseObject) {
            [self.tableView.mj_header beginRefreshing];
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }else if (type == HECartTabBarActionTypeSettlement) {
        // 结算
        NSMutableArray *arr = [NSMutableArray array];
        for (HEShopCarHeadModel *head in self.cartsDataSource) {
            for (HEShopCarModel *good in head.goodsList) {
                if (good.isChoose) {
                    [arr addObject:[NSNumber numberWithInteger:good.id]];
                }
            }
        }
        
        if (arr.count == 0) {
            [Dialog toast:@"请选择要下单的商品~" delay:2.0];
            return;
        }
        
        HECreateOrderViewController *vc = [HECreateOrderViewController new];
        vc.previewType = HESubmitPreviewTypeByCart;
        vc.previewModel.cartIds = [arr componentsJoinedByString:@","];
        vc.previewModel.type = 2;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)calculateEnd {
    
    BOOL isAllSelect = YES;
    NSInteger total = 0;
    CGFloat totalPrice = 0.0;
    self.selectGoods = [NSMutableArray array];
    
    for (HEShopCarHeadModel *head in self.cartsDataSource) {
        if (!head.isChoose) { // 判断是否全选
            isAllSelect = NO;
        }
        for (HEShopCarModel *good in head.goodsList) {
            if (good.isChoose) {
                total += good.quantity;
                totalPrice += good.price * good.quantity;
                [self.selectGoods addObject:good];
            }
        }
    }
    
    [_tabbar updateTabDataWithSelect:isAllSelect totalPrice:totalPrice total:total];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
